<?php
namespace Frieza\Modules\Decoration\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\Decoration\Subject as mSubject;
use Doraemon\model\Decoration\Tag as mTag;
use Doraemon\service\Decoration\Cache as sCache;
use Doraemon\service\Decoration\Main as sMain;

class MainTagController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public static function edit(Request $request,$sid)
    {
        $params = $request->all();

        $param = [
            'sid'=> $params['sid'],
            'name'=> $params['name'],
            'sort'=> $params['sort'],
            'link'=> $params['link'],
            'admin_id'=>Admin::user()->id,
        ];

        if(!isset($params['id'])) {
            $param['add_time'] = date('Y-m-d H:i:s');
            $result = mTag::addData($param);
        }else{
            $result = mTag::updateData($param,['id'=>$params['id']]);
        }

        if($result){
            sCache::updateCache();

            $success = new MessageBag([
                'title' => '操作成功'
            ]);

            return redirect('/admin/decoration/tag/'.$sid)->with(compact('success'));
        }else{
            $error = new MessageBag([
                'title' => $result
            ]);

            return back()->with(compact('error'));
        }

    }

    public static function del($id, $sid)
    {
        $data = ['status'=>mTag::STATUS_DELETE];
        $result = mTag::updateData($data, ['id'=>$id]);

        if($result){
            sCache::updateCache();

            $success = new MessageBag([
                'title' => '操作成功'
            ]);

            return redirect('/admin/decoration/tag/'.$sid)->with(compact('success'));
        }else{
            $error = new MessageBag([
                'title' => $result
            ]);

            return back()->with(compact('error'));
        }
    }

    public function index(Request $request,Content $content,$sid = 0){;
        $request = $request->all();
        $codition = self::_filterWhere($request);

        $subject = mSubject::getOneByWhere(['status'=>mSubject::STATUS_OPEN ,'id'=>$sid],['id','name']);
        return $content
            ->header($subject['name'].'-热搜词')
            ->breadcrumb(
                ['text' => '主题列表', 'url' => '/decoration/mainsubject'],
                ['text' => $subject['name'].'-热搜词', 'url' => '/decoration/maintag/'.$sid]
            )
            ->body(self::tagsList($request,$codition, $sid));
    }

    private function _filterWhere($params){
        if(isset($params['_columns_'])){
            unset($params['_columns_']);
        }
        if(isset($params['_pjax'])){
            unset($params['_pjax']);
        }

        $data = [];
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);

        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
              //  $where[$_k] = $_v;
                if($_k == 'date_time') {
                    if ($where[$_k]['start'] <> '') {
                        $where['start_time[>=]'] = $where[$_k]['start'];
                        unset($where[$_k]['start']);
                    }
                    if ($where[$_k]['end'] <> '') {
                        $where['end_time[<]'] = $where[$_k]['end'];
                        $where[$_k]['end'];
                    }
                    unset($where[$_k]);
                }
            }
        }
        $where['status'] = isset($params['status']) ? : mTag::STATUS_OPEN;

        $data = [
            'LIMIT' => $limit,
        ];
        $data['ORDER'] = ['sort' => 'DESC'];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }

    public function tags($request, $subjects, $sid){

        if(!empty($request['AND']['id'])){
            $data = mTag::getOneByWhere(['id'=>$request['AND']['id']]);
        }else{
            $data = [];
        }

        $form = new Form($data);

        if(isset($request['AND']['id'])){
            $form->hidden('id');
        }

        $form->select('sid','隶属主题')->options($subjects)->default($sid)->setWidth(4, 2)->required('不能为空');
        $form->text('name', '名称')->setWidth(4, 2)->required('不能为空');
        $form->text('sort', '权重')->setWidth(4, 2)->required('不能为空');
        $form->text('link', '跳转链接')->setWidth(4, 2)->default('hhz://search-tag:')->required('不能为空');

        $form->action('/admin/decoration/tag/edit/'.$sid);

        return $form->render();
    }

    public function tagsList($request = [], $condition = [], $sid){
        if($sid > 0) {
            if (isset($condition['AND'])) {
                $condition['AND']['sid'] = $sid;
            } else {
                $condition['sid'] = $sid;
            }
        }

        $tag_info =  mTag::getAllByWhere($condition);
        unset($condition['LIMIT']);
       $total = mTag::getCount($condition);

//        $tag = sMain::gettag($request);


        $gridModel = new pGridDataModel($tag_info, $total, [
            'perPage' => self::PAGE_SIZE
        ]);


        $listGrid = Admin::grid($gridModel, function (Grid $grid)use( $sid) {
            //$grid->disableFilter();
            //$grid->disableTools();
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter)use( $sid) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter){
                    $filter->equal('name', '名称')->placeholder('请输入名称');
                });
            });

            $grid->column('id', 'id')->sort();
            $grid->column('name', '名称');
            $grid->column('sort', '权重');
            $grid->column('link', '链接');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('edit_time', '编辑时间');

            $grid->actions(function (Grid\Displayers\Actions $actions)use($sid){
                $actions->disableView();
                $actions->disableDelete();
                $actions->disableEdit();

                $actions->append("<a href=\"/admin/decoration/tag/".$sid."?id=".$actions->row->id."\" class=\"btn btn-primary\">编辑</a>");
                $actions->append("<a href=\"/admin/decoration/tag/del/".$actions->row->id. '/'. $sid. "\" class=\"btn btn-primary\" onclick=\"return confirm('确认删除！！！'); \">删除</a>");
            });

        });
        $list = $listGrid->render();
        return $list;
    }


    //排序
    public function sort(Request $request)
    {
        $params = $request->all();
        if($params['sort'] && is_array($params['sort'])){
            $params['sort']  = array_values(array_reverse(array_flip($params['sort'])));
        }

        $result = mTag::action(function()use($params){
            foreach($params['sort'] as $_k=>$id){
                if(!mTag::updateData(['sort' => $_k], ['id' => $id])){
                    return false;
                }
            }
            return true;
        });
        if($result){
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

}